import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  progress: {},
  courseProgress: {},
  notes: {},
  loading: false,
  error: null
};

const learningSlice = createSlice({
  name: 'learning',
  initialState,
  reducers: {
    setProgress: (state, action) => {
      const { courseId, chapterId, progress } = action.payload;
      if (!state.progress[courseId]) {
        state.progress[courseId] = {};
      }
      state.progress[courseId][chapterId] = {
        ...state.progress[courseId][chapterId],
        ...progress
      };
    },
    markChapterComplete: (state, action) => {
      const { courseId, chapterId, completedAt } = action.payload;
      if (!state.progress[courseId]) {
        state.progress[courseId] = {};
      }
      state.progress[courseId][chapterId] = {
        ...state.progress[courseId][chapterId],
        completed: true,
        completedAt
      };
    },
    addNote: (state, action) => {
      const { chapterId, note } = action.payload;
      if (!state.notes[chapterId]) {
        state.notes[chapterId] = [];
      }
      state.notes[chapterId].push(note);
    },
    removeNote: (state, action) => {
      const { chapterId, noteId } = action.payload;
      if (state.notes[chapterId]) {
        state.notes[chapterId] = state.notes[chapterId].filter(
          note => note.id !== noteId
        );
      }
    },
    setLoading: (state, action) => {
      state.loading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
    },
    setCourseProgress: (state, action) => {
      const { courseId, progress } = action.payload;
      state.courseProgress[courseId] = {
        ...state.courseProgress[courseId],
        ...progress,
        lastUpdated: new Date().toISOString()
      };
    }
  }
});

export const {
  setProgress,
  markChapterComplete,
  setCourseProgress,
  setLoading,
  setError,
  addNote,
  removeNote
} = learningSlice.actions;

// Thunk action creators
export const updateLearningProgress = ({ courseId, chapterId, progress }) => async (dispatch) => {
  try {
    dispatch(setLoading(true));
    // 这里应该调用 API 保存进度
    // const response = await learningApi.saveProgress({ courseId, chapterId, progress });
    dispatch(setProgress({ courseId, chapterId, progress }));

    // 如果章节完成，更新课程总进度
    if (progress.completed) {
      dispatch(calculateAndUpdateCourseProgress(courseId));
    }
  } catch (error) {
    dispatch(setError(error.message));
    throw error;
  } finally {
    dispatch(setLoading(false));
  }
};

// Thunk action creator for saving notes
export const saveNote = ({ chapterId, note }) => async (dispatch) => {
  try {
    dispatch(setLoading(true));
    // 这里应该调用 API 保存笔记
    // const response = await learningApi.saveNote({ chapterId, note });
    dispatch(addNote({ chapterId, note }));
    return note;
  } catch (error) {
    dispatch(setError(error.message));
    throw error;
  } finally {
    dispatch(setLoading(false));
  }
};

// 计算并更新课程总进度的 thunk
export const calculateAndUpdateCourseProgress = (courseId) => async (dispatch, getState) => {
  try {
    const state = getState();
    const course = state.course.courses.find(c => c.id === courseId);
    const progress = state.learning.progress[courseId] || {};

    if (!course || !course.chapters) return;

    const completedChapters = course.chapters.filter(ch => progress[ch.id]?.completed).length;
    const totalTime = Object.values(progress).reduce((total, chProgress) =>
      total + (chProgress.videoPosition || 0), 0);

    dispatch(setCourseProgress({
      courseId,
      progress: {
        completedChapters,
        totalChapters: course.chapters.length,
        totalTime,
        completionRate: Math.round((completedChapters / course.chapters.length) * 100)
      }
    }));
  } catch (error) {
    console.error('更新课程进度失败:', error);
    dispatch(setError('更新课程进度失败'));
  }
};

// 删除笔记的 thunk action creator
export const deleteNote = ({ chapterId, noteId }) => async (dispatch) => {
  try {
    dispatch(setLoading(true));
    // 这里应该调用 API 删除笔记
    // await learningApi.deleteNote({ chapterId, noteId });
    dispatch(removeNote({ chapterId, noteId }));
  } catch (error) {
    dispatch(setError(error.message));
    throw error;
  } finally {
    dispatch(setLoading(false));
  }
};

export default learningSlice.reducer; 